package com.cwt_taxi_xa.protocol.socket;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.data.SocketConfig;
import com.cwt_taxi_xa.protocol.DeviceBiz;
import com.cwt_taxi_xa.util.CompareUtil;

/**
 * 多平台中心管理
 * @author undi
 * socket连接通讯平台
 */
public class SocketManager {
    String TAG = "SocketManager";
    boolean networkIsAvailable = false;
    //目前只处理副服务器
    //public SocketClient  socketClient = new SocketClient();

    private boolean backupConfigChange = false;

    public void setBackupConfigChange(boolean backupConfigChange) {
        this.backupConfigChange = backupConfigChange;
    }

    public void startConfig(){
        if(backupConfigChange){
            connect();
            backupConfigChange = false;
        }
    }

    public void create(){
        Log.d(TAG,"create-----------------------------");
        //主副服务器地址不一样才启动
        //socketClient.create(getBackupConfig());
            //启动连接服务器
        Context context = MainApplication.getInstance();
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);//获取系统的连接服务
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();//获取网络的连接情况
        if (activeNetInfo != null) {
            if (activeNetInfo.isAvailable()) {
                Log.d(TAG, "else create----------------------------- setConnect(true)");
                setConnect(true);
            }
            if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                //判断WIFI网
            } else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                //判断3G网
            }
        }

    }

    public void sendMessage(byte[] buffer){
        //socketClient.sendMessage(buffer);
    }

    //发送905数据体(自己定义流水号)
    public void sendLocationInfoMessage(byte[] buffer){
        //socketClient.sendDataMessage(buffer);
    }
    //发送心跳
    public void sendHeartbeatMessage(){
        //socketClient.sendHeartbeatMessage();
    }

    public void setConnect(boolean connect){
        if(networkIsAvailable != connect){
           this.networkIsAvailable = connect;
           //socketClient.setConnect(connect);
        }
    }


    /**
     * 获取备份服务器
     * @return
     */
    private SocketConfig getBackupConfig(){
        String ip = DeviceBiz.getIpBak();
        String port = DeviceBiz.getPortBak();

        int switcher = DeviceBiz.getSwitcherBak();
        SocketConfig socketConfig = new SocketConfig(ip,port,switcher == 1);
        //如果主服务器与备份服务器参数相同,则关闭备份服务器
        if(CompareUtil.equals(ip,DeviceBiz.getIp()) && CompareUtil.equals(port,DeviceBiz.getPort())){
            socketConfig.setOpen(false);
        }
        return socketConfig;
    }

    //修改服务器参数后启动连接
    public void connect() {
        //socketClient.setConnect(getBackupConfig());
    }
}
